<template>
    <el-card class="industrial-card">
      <!-- 工业风格顶部导航 -->
      <header class="industrial-header">
        <div class="header-left">
          <h1>入库管理</h1>
        </div>
        <div class="header-center">
          <p class="industrial-clock">{{ currentTime }}</p>
        </div>
        <div class="header-right">
          <p class="industrial-developer">十四事业部装备中心开发</p>
        </div>
      </header>
  
      <!-- 扫码控制区 -->
      <div class="industrial-control-panel">
        <div class="scan-section">
          <div class="scan-input-group">
            <span class="industrial-label">货架码：</span>
            <el-input 
              v-model="HJcode" 
              class="industrial-input" 
              placeholder="请扫货架码" 
              disabled 
            />
            <el-button 
              type="warning" 
              class="industrial-button"
              @click="skipLocation"
            >
              跳过当前位置
            </el-button>
            <el-button 
              type="primary" 
              class="industrial-button"
              @click="resetPage"
            >
              重置页面
            </el-button>
          </div>
  
          <div class="serial-control">
            <el-button 
              type="primary" 
              plain 
              class="industrial-button"
              @click="openPort"
            >
              连接串口
            </el-button>
            <el-button 
              type="danger" 
              plain 
              class="industrial-button"
              @click="closePort"
            >
              关闭串口
            </el-button>
            <div class="industrial-status-indicator" :style="serialColor"></div>
          </div>
        </div>
      </div>
  
      <!-- 产品展示区 -->
      <div class="industrial-grid-container">
        <div 
            v-for="(product, index) in products" 
            :key="index"
            class="industrial-grid-item"
            :class="{
              'active': product.scanned,
              'completed': product.code,
              'duplicate-highlight': duplicateIndex === index
            }"
            @click="focusProduct(index)"
          >
          <div class="product-slot">
            <span class="slot-label">总成{{ index + 1 }}</span>
            <span v-if="product.code" class="product-code">{{ product.code }}</span>
            <span v-else class="scan-prompt">待扫描</span>
          </div>
          
        </div>
      </div>
  
      <!-- 操作状态提示 -->
      <div class="industrial-status-bar">
        <div class="status-message">
          {{ statusMessage }}
        </div>
        <div class="progress-indicator">
          进度: {{ scannedCount }}/6
        </div>
      </div>
      <!-- <el-button @click="scanShelf(textquery)">
            货架
      </el-button>
      <el-button @click="scanProduct(textquery)">
            产品
      </el-button>
      <el-input v-model="textquery">
      </el-input> -->
      <!-- 完成提示弹窗 -->
      <!-- <el-dialog
        v-model="showCompletionDialog"
        title="入库完成"
        width="30%"
        center
      >
        <span>货架 {{ HJcode }} 的6个产品已全部入库</span>
        <template #footer>
          <el-button 
            type="primary"
            @click="resetPage"
          >
            开始新货架入库
          </el-button>
        </template>
      </el-dialog> -->
    </el-card>
</template>
  
<script setup lang="ts" name="入库管理">
  import { ref, onMounted, onUnmounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import request from '/@/utils/request';
  
//测试
 const textquery = ref('');
 

  // 当前时间显示
  const currentTime = ref('');
  let timer: number;
  
  const updateTime = () => {
    const now = new Date();
    currentTime.value = now.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });
  };
  
  onMounted(() => {
    updateTime();
    timer = window.setInterval(updateTime, 1000);
  });
  
  onUnmounted(() => {
    clearInterval(timer);
  });
  
  // 产品数据
  const products = ref(Array(6).fill().map(() => ({
  code: '',
  scanned: false,
  skipped: false
  })));
  const HJcode = ref('');
  const scannedCount = ref(0);
  const statusMessage = ref('请先扫描货架码');
  const showCompletionDialog = ref(false);
  const currentFocusIndex = ref(-1);
  const HJRegex= /^EHS.*$/;
  
  // 串口相关
  const serialColor = ref('background-color:red');
  const port = ref(null);
  const reader = ref(null);
  const textSN = ref('');
  
  // 扫描货架码
  const scanShelf = (code: string) => {
    HJcode.value = code;
    statusMessage.value = `货架 ${code} 已扫描，请开始扫描产品`;
    ElMessage.success(`货架 ${code} 扫描成功`);
  };
  
// 获取已扫描数量（包括跳过的）
const getScannedCount = () => {
  return products.value.filter(p => p.scanned || p.skipped).length;
};


const duplicateIndex = ref(-1); // 存储重复条码的位置索引
  // 扫描产品
const scanProduct = (code: string) => {
  // 检查条码是否已存在
  const existingIndex = products.value.findIndex(p => p.code === code);
  if (existingIndex !== -1) {
    duplicateIndex.value = existingIndex;
    ElMessage.warning(`产品 ${code} 已在位置 ${existingIndex + 1} 扫描过`);
    
    // 3秒后清除高亮
    setTimeout(() => {
      duplicateIndex.value = -1;
    }, 3000);
    
    return;
  }
    if (currentFocusIndex.value === -1) {
    const firstEmptyIndex = products.value.findIndex(p => !p.scanned && !p.skipped);
    if (firstEmptyIndex !== -1) {
      currentFocusIndex.value = firstEmptyIndex;
    } else {
      ElMessage.warning('所有位置已完成');
      return;
    }
    }

  const product = products.value[currentFocusIndex.value];
  product.code = code;
  product.scanned = true;
  scannedCount.value = getScannedCount(); // 使用新计数方法
    
  statusMessage.value = `产品 ${code} 已扫描到位置 ${currentFocusIndex.value + 1}`;
  ElMessage.success(`产品 ${code} 扫描成功`);
    
    // 检查是否全部完成
    if (scannedCount.value === 6) {
      completeInventory();
    }
    
    // 自动移动到下一个未扫描的位置
    const nextIndex = products.value.findIndex(p => !p.scanned);
    currentFocusIndex.value = nextIndex !== -1 ? nextIndex : -1;
  };
  
  // 完成入库
  const completeInventory = async () => {
    try {
      // 调用API绑定货架和产品
      // await bindShelfAndProducts(HJcode.value, products.value.map(p => p.code));
      request({
              url: '/api/StockInRecord/ScanAdd',
              method: 'post',
              data: {
                  'hjCode':HJcode.value,
                  'stacks':products.value,
                    }
              }).then(res => {
                if(res.Success){
                  statusMessage.value = `货架 ${HJcode.value} 入库完成`;
                  ElMessage.success('入库成功');
                  resetPage();
                }
                else{
                  statusMessage.value= res.Mesg;
                  ElMessage.error('入库提交失败: ' + res.Mesg);
                }
              })
      //showCompletionDialog.value = true;
     
      
    } catch (error) {
      ElMessage.error('入库提交失败: ' + error.message);
    }
  };
  
  // 重置页面
  const resetPage = () => {
    HJcode.value = '';
    products.value = Array(6).fill().map(() => ({
    code: '',
    scanned: false,
    skipped: false
    }));
    scannedCount.value = 0;
    statusMessage.value = '请扫描新的货架码';
    showCompletionDialog.value = false;
    currentFocusIndex.value = -1;
  };
  
 // 跳过当前位置
const skipLocation = () => {
  if (currentFocusIndex.value !== -1) {
    products.value[currentFocusIndex.value].skipped = true;
    products.value[currentFocusIndex.value].scanned = true; // 标记为已扫描
    scannedCount.value = getScannedCount(); // 更新计数
    
    ElMessage.info(`位置 ${currentFocusIndex.value + 1} 已跳过`);
    
    // 自动移动到下一个未处理的位置
    const nextIndex = products.value.findIndex(p => !p.scanned && !p.skipped);
    currentFocusIndex.value = nextIndex !== -1 ? nextIndex : -1;
    
    // 检查是否全部完成
    if (scannedCount.value === 6) {
      completeInventory();
    }
  }
  else{
    products.value[0].skipped = true;
    products.value[0].scanned = true; // 标记为已扫描
    scannedCount.value = getScannedCount(); // 更新计数
    
    ElMessage.info(`位置 ${1} 已跳过`);
    
    // 自动移动到下一个未处理的位置
    const nextIndex = products.value.findIndex(p => !p.scanned && !p.skipped);
    currentFocusIndex.value = nextIndex !== -1 ? nextIndex : -1;
    
    // 检查是否全部完成
    if (scannedCount.value === 6) {
      completeInventory();
    }
  }
};
  
  // 聚焦产品位置
  const focusProduct = (index: number) => {
    if (HJcode.value && !products.value[index].code) {
      currentFocusIndex.value = index;
      ElMessage.info(`已选择位置 ${index + 1} 准备扫描`);
    }
  };
  
  // 串口操作 (保持原有实现)
  //打开串口
const openPort = async () => {
    try {
        port.value = await navigator.serial.requestPort();
        await port.value.open({ baudRate: 115200 });
    } 
    catch (error) {
        alert("打开串口失败："+error)
    }

    if (port.value && port.value.readable){

        serialColor.value = "background-color:green;width:30px;height:30px";
    }
    else
    {
        serialColor.value = "background-color:red;width:30px;height:30px";
    }

    await readPort();
};

//关闭串口
const closePort = () => {

    if (reader.value) 
    {
        reader.value.cancel();
    }

    if (port.value) 
    {
        port.value.close();
    }
    
    if (port.value && port.value.readable)
    {
        serialColor.value = "background-color:green;width:30px;height:30px";
    }
    else
    {
        serialColor.value = "background-color:red;width:30px;height:30px";
    }
};

//读取串口
const readPort = async () => {
    textSN.value = "";
    if (port.value && port.value.readable) {

        reader.value = port.value.readable.getReader();
        try {
            var flag = true
            while (true) 
            {

                const { value, done } = await reader.value.read();
                if (done) 
                {
                    textSN.value = value;
                    break;
                }

                for (let i = 0; i < value.length; i++) 
                {
                    if(!flag)
                    {
                        flag = true
                        textSN.value = ''
                    }
                    textSN.value += String.fromCharCode(value[i]);
                    if (value[i] === 13) 
                    {
                        flag = false
                        // 扫码完成
                        //console.log("ss",textSN.value)
                        textSN.value = textSN.value.replace('\r','').replace('\n', '').trim()
                        //virtualSN.value = textSN.value
                        if (!HJcode.value) 
                        {
                          if(textSN.value.match(HJRegex)){
                            scanShelf(textSN.value);
                          }
                          else{
                            ElMessage.error('条码不符合或货架码规则');
                          }
                            
                        } 
                        else 
                        {
                            scanProduct(textSN.value);
                        }                        
                    }
                }
            }

        } 
        catch (error) 
        {
            console.error(error);
        } 
        finally 
        {
            if (reader.value) {
                reader.value.releaseLock();
            }
        }
    }
};
</script>
<style scoped lang="scss">
  /* 工业深色主题 */
  :root {
    --industrial-dark: #1a1d23;
    --industrial-darker: #06469f;
    --industrial-accent: #3a4a6b;
    --industrial-metal: #6b7a8f;
    --industrial-highlight: #4d7c8a;
    --industrial-success: #2c8a5d;
    --industrial-warning: #8a6e2c;
    --industrial-danger: #8a2c2c;
    --industrial-text: #e0e0e0;
    --industrial-text-secondary: #b0b0b0;
  }
  
  /* 工业风格卡片 */
  .industrial-card {
    background-color: #f0f6f4;
    border: 1px solid #6b7a8f;
    border-radius: 4px;
    color: #e0e0e0;
    padding: 16px;
  }
  
  /* 工业风格头部 */
  .industrial-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 20px;
    background-color: #06469f;
    border-bottom: 2px solid #3a4a6b;
    margin-bottom: 20px;
    
    .header-left h1 {
      margin: 0;
      font-size: 22px;
      font-weight: bold;
      color: #e0e0e0;
      letter-spacing: 1px;
    }
    
    .industrial-clock {
      font-family: 'Courier New', monospace;
      font-size: 16px;
      color: #f1f6f8;
    }
    
    .industrial-developer {
      font-size: 14px;
      color: #b0b0b0;
    }
  }
  
  /* 控制面板 */
  .industrial-control-panel {
    background-color: #06469f;
    border: 1px solid #6b7a8f;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 20px;
  }
  
  .scan-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .scan-input-group {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
  
  .industrial-label {
    font-weight: bold;
    color: #b0b0b0;
    min-width: 60px;
  }
  
  .industrial-input {
    width: 250px;
    
    :deep(.el-input__inner) {
      background-color: #eceff2;
      border: 1px solid #06469f;
      color: #24a4ea;
      border-radius: 2px;
      height: 36px;
      font-family: monospace;
    }
  }
  
  .serial-control {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .industrial-button {
    border-radius: 2px;
    font-weight: 600;
    height: 36px;
    letter-spacing: 0.5px;
    
  }
  
  .el-button {
    &.el-button--primary {
    background-color: #e8eaef;
    color: #0fa0ee;
    &:hover {
      background-color: #e1d8d8;
    }
  }
  &.el-button--warning {
    background-color: #e8eaef;
    color: #e0c410;
    &:hover {
      background-color: #e1d8d8;
    }
  }
 }

  .industrial-status-indicator {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 2px solid #6b7a8f;
    box-shadow: 0 0 8px currentColor;
  }
  
  /* 产品网格布局 */
  .industrial-grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;
  }
  
  .industrial-grid-item {
    height: 150px;
    background-color: #06469f;
    border: 2px solid #6b7a8f;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s;
    cursor: pointer;
    position: relative;
    &.skipped {
    background-color: rgba(138, 110, 44, 0.2); /* 警告色背景 */
    border-color: #8a6e2c;
    
    .scan-prompt::after {
      content: "(已跳过)";
      color: #8a6e2c;
      margin-left: 5px;
    }
  }
  &.duplicate-highlight {
    animation: duplicate-feedback 0.5s 3, border-blink 1s infinite;
    position: relative;
    overflow: hidden;
    
    &::after {
      content: "重复扫码";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      background: rgba(232, 6, 6, 0.7);
      color: white;
      text-align: center;
      font-weight: bold;
      padding: 2px 0;
    }
    
    .product-code {
      color: #ff0000;
      text-decoration: underline;
    }
  }
    &.active {
      border-color: #4d7c8a;
      box-shadow: 0 0 10px rgba(77, 124, 138, 0.5);
    }
    
    &.completed {
      background-color: rgba(44, 138, 93, 0.2);
      border-color: #2c8a5d;
    }
  }

  @keyframes duplicate-pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}
  
  .product-slot {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }
  
  .slot-label {
    font-size: 18px;
    font-weight: bold;
    color: #b0b0b0;
  }
  
  .product-code {
    font-size: 16px;
    font-family: monospace;
    color: #2c8a5d;
    font-weight: bold;
  }
  
  .scan-prompt {
    font-size: 14px;
    color: #b0b0b0;
    font-style: italic;
  }
  
  /* 状态栏 */
  .industrial-status-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background-color: #06469f;
    border: 1px solid #6b7a8f;
    border-radius: 4px;
  }
  
  .status-message {
    color: #e0e0e0;
    font-weight: 500;
  }
  
  .progress-indicator {
    color: #29e542;
    font-weight: bold;
    font-family: monospace;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .industrial-grid-container {
      grid-template-columns: repeat(2, 1fr);
    }
    
    .scan-section {
      flex-direction: column;
      align-items: flex-start;
    }
    
    .industrial-input {
      width: 100%;
    }
  }
</style>